import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Select,
  Space,
  Tag,
  Modal,
  message,
  Popconfirm,
  Card,
  Input,
  DatePicker
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckOutlined,
  CloseOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import moment from 'moment';

const { Option } = Select;
const { RangePicker } = DatePicker;

const BookingList = () => {
  const [bookings, setBookings] = useState([]);
  const [loading, setLoading] = useState(false);
  const [statusFilter, setStatusFilter] = useState('');
  const [searchKeyword, setSearchKeyword] = useState('');
  const [dateRange, setDateRange] = useState([]);
  const { user, isAdmin, isTeacher, isStudent } = useAuth();
  const navigate = useNavigate();

  useEffect(() => {
    loadBookings();
  }, []);

  const loadBookings = async () => {
    try {
      setLoading(true);
      let data;
      if (isStudent()) {
        data = await apiService.getBookingsByStudent(user.relatedId);
      } else if (isTeacher()) {
        // 获取教师的所有课程的预订
        const courses = await apiService.getCoursesByTeacher(user.relatedId);
        const allBookings = [];
        for (const course of courses) {
          const courseBookings = await apiService.getBookingsByCourse(course.id);
          allBookings.push(...courseBookings);
        }
        data = allBookings;
      } else {
        data = await apiService.getBookings();
      }
      setBookings(data);
    } catch (error) {
      message.error('加载预订列表失败');
      console.error('加载预订失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleStatusFilter = (status) => {
    setStatusFilter(status);
  };

  const handleSearch = () => {
    // 实现搜索逻辑
  };

  const handleUpdateStatus = async (bookingId, status) => {
    try {
      await apiService.updateBookingStatus(bookingId, status);
      message.success('状态更新成功');
      loadBookings();
    } catch (error) {
      message.error('状态更新失败: ' + (error.response?.data?.message || error.message));
      console.error('更新预订状态失败:', error);
    }
  };

  const handleCancel = async (bookingId) => {
    try {
      await apiService.cancelBooking(bookingId);
      message.success('取消预订成功');
      loadBookings();
    } catch (error) {
      message.error('取消预订失败: ' + (error.response?.data?.message || error.message));
      console.error('取消预订失败:', error);
    }
  };

  const handleDelete = async (bookingId) => {
    try {
      await apiService.deleteBooking(bookingId);
      message.success('删除成功');
      loadBookings();
    } catch (error) {
      message.error('删除失败: ' + (error.response?.data?.message || error.message));
      console.error('删除预订失败:', error);
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'PENDING':
        return 'orange';
      case 'CONFIRMED':
        return 'green';
      case 'CANCELLED':
        return 'red';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'PENDING':
        return '待确认';
      case 'CONFIRMED':
        return '已确认';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  };

  // 过滤数据
  const filteredBookings = bookings.filter(booking => {
    let matches = true;

    // 状态过滤
    if (statusFilter && booking.status !== statusFilter) {
      matches = false;
    }

    // 关键词搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      const courseName = booking.course?.name?.toLowerCase() || '';
      const studentName = booking.student?.name?.toLowerCase() || '';
      const courseCode = booking.course?.code?.toLowerCase() || '';
      
      if (!courseName.includes(keyword) && 
          !studentName.includes(keyword) && 
          !courseCode.includes(keyword)) {
        matches = false;
      }
    }

    // 日期范围过滤
    if (dateRange.length === 2) {
      const bookingDate = moment(booking.createdAt);
      if (!bookingDate.isBetween(dateRange[0], dateRange[1], 'day', '[]')) {
        matches = false;
      }
    }

    return matches;
  });

  const columns = [
    {
      title: '预订ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '课程名称',
      dataIndex: ['course', 'name'],
      key: 'courseName',
      render: (text, record) => (
        <Button
          type="link"
          onClick={() => navigate(`/courses/${record.course.id}`)}
        >
          {text}
        </Button>
      )
    },
    {
      title: '课程代码',
      dataIndex: ['course', 'code'],
      key: 'courseCode'
    },
    {
      title: '学生姓名',
      dataIndex: ['student', 'name'],
      key: 'studentName',
      render: (text, record) => {
        if (isAdmin()) {
          return (
            <Button
              type="link"
              onClick={() => record && record.student && navigate(`/students/${record.student.id}`)}
            >
              {text}
            </Button>
          );
        }
        return text;
      }
    },
    {
      title: '学号',
      dataIndex: ['student', 'studentId'],
      key: 'studentId'
    },
    {
      title: '预订时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm'),
      sorter: (a, b) => moment(a.createdAt).unix() - moment(b.createdAt).unix()
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      ),
      filters: [
        { text: '待确认', value: 'PENDING' },
        { text: '已确认', value: 'CONFIRMED' },
        { text: '已取消', value: 'CANCELLED' }
      ],
      onFilter: (value, record) => record.status === value
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => record && navigate(`/bookings/${record.id}`)}
          >
            查看详情
          </Button>
          <Button
            type="link"
            onClick={() => record && record.course && navigate(`/courses/${record.course.id}`)}
          >
            查看课程
          </Button>
          
          {/* 学生操作 */}
          {isStudent() && record.status === 'PENDING' && (
            <Popconfirm
              title="确定要取消这个预订吗？"
              onConfirm={() => record && handleCancel(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="link"
                danger
                icon={<CloseOutlined />}
              >
                取消预订
              </Button>
            </Popconfirm>
          )}

          {/* 教师操作 */}
          {isTeacher() && record.status === 'PENDING' && (
            <>
              <Button
                type="link"
                icon={<CheckOutlined />}
                onClick={() => record && handleUpdateStatus(record.id, 'CONFIRMED')}
              >
                确认
              </Button>
              <Button
                type="link"
                danger
                icon={<CloseOutlined />}
                onClick={() => record && handleUpdateStatus(record.id, 'CANCELLED')}
              >
                拒绝
              </Button>
            </>
          )}

          {/* 管理员操作 */}
          {isAdmin() && (
            <>
              {record.status === 'PENDING' && (
                <>
                  <Button
                    type="link"
                    icon={<CheckOutlined />}
                    onClick={() => record && handleUpdateStatus(record.id, 'CONFIRMED')}
                  >
                    确认
                  </Button>
                  <Button
                    type="link"
                    danger
                    icon={<CloseOutlined />}
                    onClick={() => record && handleUpdateStatus(record.id, 'CANCELLED')}
                  >
                    拒绝
                  </Button>
                </>
              )}
              <Popconfirm
                title="确定要删除这个预订吗？"
                onConfirm={() => record && handleDelete(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="link"
                  danger
                  icon={<DeleteOutlined />}
                >
                  删除
                </Button>
              </Popconfirm>
            </>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space wrap>
            <Input
              placeholder="搜索课程名称、学生姓名或课程代码"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            
            <Select
              placeholder="筛选状态"
              value={statusFilter}
              onChange={handleStatusFilter}
              style={{ width: 120 }}
              allowClear
            >
              <Option value="PENDING">待确认</Option>
              <Option value="CONFIRMED">已确认</Option>
              <Option value="CANCELLED">已取消</Option>
            </Select>

            <RangePicker
              placeholder={['开始日期', '结束日期']}
              value={dateRange}
              onChange={setDateRange}
              style={{ width: 240 }}
            />

            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={handleSearch}
            >
              搜索
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={filteredBookings}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条预订记录`,
            defaultPageSize: 10,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
          scroll={{ x: 1200 }}
        />
      </Card>
    </div>
  );
};

export default BookingList;